package com.efesco.system;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;

import com.bstek.dorado.common.ds.ConnectionHelper;
import com.efesco.common.*;

public class LoginServlet extends HttpServlet {

	private static final String CONTENT_TYPE = "text/html; charset=GBK";

	/** Initialize global variables */
	public void init() throws ServletException {
	}

	/** Process the HTTP Get request */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType(CONTENT_TYPE);
		
		String userName = request.getParameter("userName");
	    String password = request.getParameter("password");
		String sql="select user_id,employee_id,single_company_id,"
		      +"foreign_enterprise_id,role_type,for_employee_id,real_name from s_user where "
		      +"user_name=? and password=?";
		User user=null;
		Connection connection=null;
		String url="";
		try {
			connection = ConnectionHelper.getConnection(null);
			PreparedStatement st = connection.prepareStatement(sql);// .createStatement();
			st.setString(1,userName);
			st.setString(2,password);
			ResultSet rs = st.executeQuery();
			if(rs.next()){
				  int userId=rs.getInt(1);
				  String empId=rs.getString(2);
				  String comId=rs.getString(3);
				  String fornId=rs.getString(4);
				  String forEmpId=rs.getString(6);
				  int role=rs.getInt(5);
				  String realName=rs.getString(7);
				  user=new User(userId,userName,empId,comId,fornId,forEmpId,role,realName);	

				  HttpSession session = request.getSession(true);
				  session.setAttribute("User", user);
					
				  url=UrlMap.mapJspUrl("main.jsp");
				  RequestDispatcher rd = this.getServletContext()
							.getRequestDispatcher("/jsp/main.jsp");
				  rd.forward(request, response);
			}
			rs.close();
			st.close();
						
			
			
		} catch (Exception e) {
			url = UrlMap.mapJspUrl("index.jsp");
			request.setAttribute("p_msg", e.toString());
			RequestDispatcher rd = this.getServletContext()
					.getRequestDispatcher(url);
			rd.forward(request, response);
			e.printStackTrace();
		}finally{
			try{
				connection.close();
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		if(user==null){
			RequestDispatcher rd = this.getServletContext()
			.getRequestDispatcher("/jsp/index.jsp");
	        rd.forward(request, response);
		}

	}
}
